import React, { FC, useEffect, useState } from 'react'
import { Pagination } from 'antd'
import {
  LIST_DEFAULT_PAGE_SIZE,
  LIST_PAGE_PARAM_KEY,
  LIST_PAGESIZE_PARAM_KEY,
} from '../constant/index'
import { useSearchParams, useNavigate, useLocation } from 'react-router-dom'

type PropsType = {
  total: number
}

const TPageControl: FC<PropsType> = (props: PropsType) => {
  const { total } = props
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(LIST_DEFAULT_PAGE_SIZE)

  const [searchParams] = useSearchParams()

  useEffect(() => {
    // 获取分页页码
    const page = parseInt(searchParams.get(LIST_PAGE_PARAM_KEY) || '') || 1
    setCurrentPage(page)
    // 分页大小
    const pageSize =
      parseInt(searchParams.get(LIST_PAGESIZE_PARAM_KEY) || '') || LIST_DEFAULT_PAGE_SIZE
    setPageSize(pageSize)
  }, [searchParams])

  //当分页的页码page/pageSize改变,需要跳转页面(改变url参数)
  const nav = useNavigate()
  const { pathname } = useLocation()
  function handlePageChange(page: number, pageSize: number) {
    // 更新要跳转的的url参数
    searchParams.set(LIST_PAGE_PARAM_KEY, page.toString())
    searchParams.set(LIST_PAGESIZE_PARAM_KEY, pageSize.toString())
    nav({
      pathname,
      search: searchParams.toString(),
    })
  }

  return (
    <Pagination
      current={currentPage}
      pageSize={pageSize}
      total={total}
      onChange={handlePageChange}
    />
  )
}

export default TPageControl
